package com.haulmont.asu.web.ui.diploma_project;

import com.haulmont.asu.entity.CathedralConsultant;
import com.haulmont.asu.entity.DiplomaProject;
import com.haulmont.asu.entity.DiplomaStudent;
import com.haulmont.cuba.gui.components.AbstractEditor;
import com.haulmont.cuba.gui.components.TextField;
import com.haulmont.cuba.gui.data.CollectionDatasource;
import com.haulmont.cuba.gui.data.Datasource;
import com.haulmont.cuba.gui.data.impl.CollectionDsListenerAdapter;

import javax.annotation.Nullable;
import javax.inject.Inject;
import java.util.Collections;
import java.util.UUID;

/**
 * Author: Sergey42
 * Date: 09.11.13 7:24
 */
public class DiplomaEditor extends AbstractEditor<DiplomaProject> {

    @Inject
    protected TextField studentGroupTF;
    @Inject
    protected TextField bookNumberTF;

    @Inject
    protected CollectionDatasource<DiplomaStudent, UUID> studentDs;
    @Inject
    protected CollectionDatasource<CathedralConsultant, UUID> poConsultantDs;
    @Inject
    protected CollectionDatasource<CathedralConsultant, UUID> lsConsultantDs;

    @Override
    protected void initItem(DiplomaProject item) {

        poConsultantDs.setQuery("select c from ext$CathedralConsultant c where c.cathedra.id = :custom$id");
        poConsultantDs.refresh(Collections.<String, Object>singletonMap("id", UUID.fromString("c96e4209-16ea-4026-b3e3-1b53b9397ed6")));

        lsConsultantDs.setQuery("select c from ext$CathedralConsultant c where c.cathedra.id = :custom$id");
        lsConsultantDs.refresh(Collections.<String, Object>singletonMap("id", UUID.fromString("a2dd7b83-b49b-4d6f-8232-1af97a138a23")));

        studentDs.addListener(new CollectionDsListenerAdapter<DiplomaStudent>() {
            @Override
            public void itemChanged(Datasource<DiplomaStudent> ds, @Nullable DiplomaStudent prevItem, @Nullable DiplomaStudent item) {
                String studentGroup = item != null ? item.getStudent().getStudentGroup().getNumber() : null;
                String bookNumber = item != null ? item.getStudent().getBookNumber() : "";

                studentGroupTF.setEditable(true);
                bookNumberTF.setEditable(true);
                studentGroupTF.setValue(studentGroup);
                bookNumberTF.setValue(bookNumber);
                studentGroupTF.setEditable(false);
                bookNumberTF.setEditable(false);
            }
        });
    }
}
